<script lang="ts" setup>
import { reactive, ref, watchEffect } from 'vue';

import { storeToRefs } from '@vben/stores';

import {
  Form,
  FormItem,
  Input,
  message,
  Select,
  Space,
  Spin,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import { linklnfos, propertySelect } from '#/api/iot/alarm/config';
import { thingModelSeverList } from '#/api/iot/product/thingModel';
import { useMqttStore } from '#/store/mqtt';

import mqttService from '../../mqtt';

const useMqtt = useMqttStore();
const { mqttOption, upTheme } = storeToRefs(useMqtt);

watchEffect(async () => {
  if (mqttOption.value.productId) {
    await getThingModelSelect(mqttOption.value.productId as string);
    await getMqttlnfos(mqttOption.value.deviceId as string);
  }
});
const spinning = ref(false);
const formState: any = ref({
  blocks: [
    {
      blockIdentifier: undefined,
      properties: {},
    },
  ],
});
const option = reactive<{
  clientId: string;
  password: string;
  username: string;
}>({
  clientId: '',
  password: '',
  username: '',
});
const severOptions = ref<{ blockName: string; id: string }[]>([]); // 服务数据
const propertyOption = ref<{ id: number; identifier: string; name: string }[]>(
  [],
); // 属性下拉

// 获取服务数据下拉数据源
async function getThingModelSelect(id: string) {
  const res = await thingModelSeverList(id);
  severOptions.value = res;
}

// 获取属性下拉数据源
async function getPropertySelect(id: number) {
  spinning.value = true;
  const res = await propertySelect(id);
  propertyOption.value = res;
  spinning.value = false;
}
// 服务下拉事件
async function handleModelChange(option: any) {
  await getPropertySelect(option.id);
  formState.value.blocks[0].blockIdentifier = option.blockIdentifier;
}
// 获取 mqtt参数
async function getMqttlnfos(id: string) {
  const res = await linklnfos(id);
  option.username = res.username;
  option.password = res.password;
  option.clientId = res.clientId;

  const mqttUrl = `ws://${res.host}:${res.webPort}/mqtt`;
  connect(mqttUrl); // 等待连接成功
}
function isEmpty(value: any): boolean {
  return value === '' || value === null || value === undefined;
}

function checkProperties(): boolean {
  const properties = formState.value.blocks[0].properties;

  // 判断 properties 对象是否为空
  if (Object.keys(properties).length === 0) {
    message.warning('请填写属性内容');
    return false;
  }

  // 判断 properties 中的每个字段是否为空
  for (const key in properties) {
    if (isEmpty(properties[key])) {
      message.warning(`请填写属性内容`);
      return false;
    }
  }

  return true;
}

function onSubmit() {
  if (checkProperties()) {
    publish(upTheme.value, JSON.stringify(formState.value));
  }
}

function onReset() {
  formState.value.blocks[0].properties = {};
}
// 连接 MQTT
function connect(mqttUrl: string) {
  mqttService.connect(mqttUrl, option);
  useMqtt.setMqttTable({
    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    type: '连接成功',
    content: `Connection is success`,
  });
  subscribe(upTheme.value);
}
// 订阅 MQTT
function subscribe(topic: string) {
  mqttService.subscribe(topic); // Subscribe to the topic
  useMqtt.setMqttTable({
    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    type: '订阅主题',
    content: `Topic:${upTheme.value}`,
  });
}
//  MQTT 传值
function publish(topic: string, value: string) {
  console.log(`Publishing to topic: ${topic}, value: ${value}`);

  mqttService.publish(topic, value); // Publish a message to the topic
  useMqtt.setMqttTable({
    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    type: '设备上行',
    content: `Content:${JSON.stringify(value)}`,
  });
}
</script>
<template>
  <div>
    <Form :model="formState" layout="vertical">
      <FormItem>
        <Select
          v-model:value="formState.blocks[0].blockIdentifier"
          placeholder="请选择模块"
          :options="severOptions"
          :field-names="{
            label: 'blockName',
            value: 'blockIdentifier',
            options: 'severOptions',
          }"
          @change="(_, option) => handleModelChange(option)"
        />
      </FormItem>
      <Spin :spinning="spinning" style="width: 100%">
        <FormItem
          v-for="item in propertyOption"
          :key="item.id"
          :label="item.name"
        >
          <Input
            v-model:value="formState.blocks[0].properties[item.identifier]"
            placeholder="请输入值"
          />
        </FormItem>
      </Spin>
      <FormItem :wrapper-col="{ span: 24, offset: 0 }">
        <Space>
          <a-button
            type="primary"
            @click="onSubmit"
            :disabled="!formState.blocks[0].blockIdentifier"
          >
            发送指令
          </a-button>
          <a-button
            :disabled="!formState.blocks[0].blockIdentifier"
            @click="onReset"
          >
            重置属性
          </a-button>
        </Space>
      </FormItem>
    </Form>
  </div>
</template>
<style scoped lang="scss"></style>
